//
//  CameraPlaybackController.m
//  IOTCamViewer
//
//  Created by tutk on 1/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AVIOCTRLDEFuserdefineds.h"

#import <sys/time.h>

#import <IOTCamera/AVIOCTRLDEFs.h>
#import "CameraPlaybackController.h"

#if defined(LIB_140210)
#import <IOTCamera/AVFRAMEINFO.h>
#import <IOTCamera/ImageBuffInfo.h>




#endif

extern unsigned int _getTickCountCamPlaB() {
    
    struct timeval tv;
    
    if (gettimeofday(&tv, NULL) != 0)
        return 0;
    
    return (unsigned int)(tv.tv_sec * 1000 + tv.tv_usec / 1000);
}

#define DEF_WAIT4STOPSHOW_TIME	250

@implementation CameraPlaybackController

#if defined(LIB_140210)

@synthesize bStopShowCompletedLock;
@synthesize mCodecId;
@synthesize glView;
@synthesize mPixelBufferPool;
@synthesize mPixelBuffer;
@synthesize mSizePixelBuffer;
#endif

@synthesize camera;
@synthesize event;
@synthesize portraitView, landscapeView;
@synthesize monitorPortrait, monitorLandscape;
@synthesize scrollViewLandscape;
@synthesize playButton, pauseButton;
@synthesize toolBar;
@synthesize statusLabel, videoInfoLabel, frameInfoLabel; 
@synthesize seekTimeLabel;
@synthesize seekTimeTotalLabel;
@synthesize playbackSlider;


- (void)timerRecording:(NSTimer *)timer {
    //recordingTimes += 1;
    NSLog(@"vvvvvvvvvvvvvvvvv timerRecording vvvvvvvvvvvvvvvvv playbackSeekTimeCurSec:%ld  playbackSeekTimeTotalSec:%ld", (unsigned long)playbackSeekTimeCurSec, (unsigned long)playbackSeekTimeTotalSec);
    
    if (isUpdateCurrentStatus && playbackSeekTimeCurSec < playbackSeekTimeTotalSec) {
        playbackSeekTimeCurSec += 1;
        [self updateViewCurrentStatus];
 
        [playbackSlider setValue:playbackSeekTimeCurSec animated:YES];

    }
}


- (void)verifyConnectionStatus
{
    if (camera.sessionState == CONNECTION_STATE_CONNECTING) {
        self.statusLabel.text = NSLocalizedString(@"Connecting...", @"");
        NSLog(@"%@ connecting", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_DISCONNECTED) {
        self.statusLabel.text = NSLocalizedString(@"Off line", @"");
        NSLog(@"%@ off line", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_UNKNOWN_DEVICE) {
        self.statusLabel.text = NSLocalizedString(@"Unknown Device", @"");
        NSLog(@"%@ unknown device", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_TIMEOUT) {
        self.statusLabel.text = NSLocalizedString(@"Timeout", @"");
        NSLog(@"%@ timeout", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_UNSUPPORTED) {
        self.statusLabel.text = NSLocalizedString(@"Unsupported", @"");
        NSLog(@"%@ unsupported", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECT_FAILED) {
        self.statusLabel.text = NSLocalizedString(@"Connect Failed", @"");
        NSLog(@"%@ connected failed", camera.uid);
    }
    
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
        
#ifndef SHOW_SESSION_MODE
        self.statusLabel.text = NSLocalizedString(@"Online", @"");
#else
        if (camera.sessionMode == CONNECTION_MODE_P2P) {
            self.connModeImageView.image = [UIImage imageNamed:@"ConnectMode_P2P"];
            self.statusLabel.text = [NSString stringWithFormat:@"%@ / P2P", NSLocalizedString(@"Online", @"")];
        }
        else if (camera.sessionMode == CONNECTION_MODE_RELAY) {
            self.connModeImageView.image = [UIImage imageNamed:@"ConnectMode_RLY"];
            self.statusLabel.text = [NSString stringWithFormat:@"%@ / Relay", NSLocalizedString(@"Online", @"")];
        }
        else if (camera.sessionMode == CONNECTION_MODE_LAN) {
            self.connModeImageView.image = [UIImage imageNamed:@"ConnectMode_LAN"];
            self.statusLabel.text = [NSString stringWithFormat:@"%@ / %@", NSLocalizedString(@"Online", @""), NSLocalizedString(@"LAN", @"")];
        }
        else {
            self.statusLabel.text = NSLocalizedString(@"Online", @"");
        }
#endif
        
        NSLog(@"%@ online", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTING) {
        self.statusLabel.text = NSLocalizedString(@"Connecting...", @"");
        NSLog(@"%@ connecting", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_DISCONNECTED) {
        self.statusLabel.text = NSLocalizedString(@"Off line", @"");
        NSLog(@"%@ off line", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_UNKNOWN_DEVICE) {
        self.statusLabel.text = NSLocalizedString(@"Unknown Device", @"");
        NSLog(@"%@ unknown device", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_WRONG_PASSWORD) {
        self.statusLabel.text = NSLocalizedString(@"Wrong Password", @"");
        NSLog(@"%@ wrong password", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_TIMEOUT) {
        self.statusLabel.text = NSLocalizedString(@"Timeout", @"");
        NSLog(@"%@ timeout", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_UNSUPPORTED) {
        self.statusLabel.text = NSLocalizedString(@"Unsupported", @"");
        NSLog(@"%@ unsupported", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_NONE) {
        self.statusLabel.text = NSLocalizedString(@"Connecting...", @"");
        NSLog(@"%@ wait for connecting", camera.uid);
    }
    
}

- (UIImage *) getUIImage:(char *)buff Width:(NSInteger)width Height:(NSInteger)height {
    
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buff, width * height * 3, NULL);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGImageRef imgRef = CGImageCreate(width, height, 8, 24, width * 3, colorSpace, kCGBitmapByteOrderDefault, provider, NULL, true,  kCGRenderingIntentDefault);
    
    
    UIImage *img = [UIImage imageWithCGImage:imgRef];
    
    
    if (imgRef != nil) {
        CGImageRelease(imgRef);
        imgRef = nil;
    }   
    
    if (colorSpace != nil) {
        CGColorSpaceRelease(colorSpace);
        colorSpace = nil;
    }
    
    if (provider != nil) {
        CGDataProviderRelease(provider);
        provider = nil;
    } 
    
    return [[img copy] autorelease];
}

- (void)showPlayButton {
    
    self.wwBtn.selected = YES;
}

- (void)showPauseButton {
    
    self.wwBtn.selected = NO;
    
}

- (void)showPlaybackNotFoundMsg {
    
    if (playbackChannelIndex < 0) {
        
        isOpened = false;
        [self showPlayButton];
        
    }
    
    tmrRecvPlayback = nil;
}

- (void)onLeftButtonClick:(id)sender{
    
    [self back:nil];
}

- (IBAction)back:(id)sender {
    
    [monitorLandscape deattachCamera];
    [monitorPortrait deattachCamera];
    
    if (playbackChannelIndex > 0) {
        
        SMsgAVIoctrlPlayRecord *req = (SMsgAVIoctrlPlayRecord *) malloc(sizeof(SMsgAVIoctrlPlayRecord));
        memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord));
        
        req->channel = 0;
        req->command = AVIOCTRL_RECORD_PLAY_STOP;
        req->stTimeDay = [Event getTimeDay:event.eventTime];
        req->Param = event.eventType;
        
        [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord)];
        
        free(req);
        
        [camera stopSoundToPhone:playbackChannelIndex];
        [camera stopShow:playbackChannelIndex];
        [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
        [camera stop:playbackChannelIndex];

    }

    [camera clearRemoteNotifications];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)play:(id)sender {

    isUpdateCurrentStatus = YES;

    if (playbackChannelIndex < 0) {
        
        isOpened = true;
        
        SMsgAVIoctrlPlayRecord *req = (SMsgAVIoctrlPlayRecord *) malloc(sizeof(SMsgAVIoctrlPlayRecord));
        memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord));
        
        req->channel = 0;
        req->command = AVIOCTRL_RECORD_PLAY_START;
        req->stTimeDay = [Event getTimeDay:event.eventTime];
        req->Param = event.eventType;
        
        [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord)];
        
        free(req);
        
        [self showPlayButton];
        
   /*     if (tmrRecvPlayback != nil) {
            
            [tmrRecvPlayback invalidate];
            tmrRecvPlayback = nil;
        }
        
        tmrRecvPlayback = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(showPlaybackNotFoundMsg) userInfo:nil repeats:nil];
        
        if (recordingTimer != nil) {
            
            [recordingTimer invalidate];
            recordingTimer = nil;
        }
        recordingTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerRecording:) userInfo:nil repeats:YES];
        //recordingTimes = 0;
        */
    }
    else {        
        [self pause:nil];
    }
    
}

- (IBAction)pause:(id)sender {

    if (playbackChannelIndex >= 0) {
        
        SMsgAVIoctrlPlayRecord *req = (SMsgAVIoctrlPlayRecord *) malloc(sizeof(SMsgAVIoctrlPlayRecord));
        memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord));
        
        req->channel = 0;
        req->command = AVIOCTRL_RECORD_PLAY_PAUSE;
        req->stTimeDay = [Event getTimeDay:event.eventTime];
        req->Param = event.eventType;
        
        [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord)];
        
        free(req);
        
    }
    
    
    isPaused = !isPaused;
    
    if (isPaused) {
        
        isUpdateCurrentStatus = NO;
        [self showPauseButton];

    } else {
        
        isUpdateCurrentStatus = YES;
        [self showPlayButton];

    }
}

#if defined(LIB_140210)
- (void)removeGLView :(BOOL)toPortrait
{
    if( glView ) {
        BOOL bRemoved = FALSE;
        if(toPortrait) {
            for (UIView *subView in self.scrollViewLandscape.subviews) {
                
                if ([subView isKindOfClass:[CameraShowGLView class]]) {
                    
                    [subView removeFromSuperview];
                    NSLog( @"glView has been removed from scrollViewLandscape <OK>" );
                    bRemoved = TRUE;
                    break;
                }
            }
            if( !bRemoved ) {
                for (UIView *subView in self.monitorPortrait.subviews) {
                    
                    if ([subView isKindOfClass:[CameraShowGLView class]]) {
                        
                        [subView removeFromSuperview];
                        NSLog( @"glView has been removed from scrollViewPortrait <OK>" );
                        //bRemoved = TRUE;  //vic seem no need???
                        break;
                    }
                }
            }
        }
        else {
            for (UIView *subView in self.monitorPortrait.subviews) {
                
                if ([subView isKindOfClass:[CameraShowGLView class]]) {
                    
                    [subView removeFromSuperview];
                    NSLog( @"glView has been removed from scrollViewPortrait <OK>" );
                    bRemoved = TRUE;
                    break;
                }
            }
            if( !bRemoved ) {
                for (UIView *subView in self.scrollViewLandscape.subviews) {
                    
                    if ([subView isKindOfClass:[CameraShowGLView class]]) {
                        
                        [subView removeFromSuperview];
                        NSLog( @"glView has been removed from scrollViewLandscape <OK>" );
                        //bRemoved = TRUE;      //vic seem no need???
                        break;
                    }
                }
            }
        }
    }
}

- (void)changeOrientation:(UIInterfaceOrientation)orientation {
    
    NSLog(@"change orientation");
    
    if (orientation == UIInterfaceOrientationLandscapeLeft ||
        orientation == UIInterfaceOrientationLandscapeRight) {
        
        [monitorPortrait deattachCamera];
        [monitorLandscape attachCamera:camera];
        
        [self removeGLView:FALSE];
        self.view = self.landscapeView;
        NSLog( @"video frame {%d,%d}%dx%d", (int)self.monitorLandscape.frame.origin.x, (int)self.monitorLandscape.frame.origin.y, (int)self.monitorLandscape.frame.size.width, (int)self.monitorLandscape.frame.size.height);
        if( glView == nil ) {
            glView = [[CameraShowGLView alloc] initWithFrame:self.monitorLandscape.frame];
            [glView setMinimumGestureLength:100 MaximumVariance:50];
            glView.delegate = self;
            [glView attachCamera:camera];
        }
        else {
            [self.glView destroyFramebuffer];
            self.glView.frame = self.monitorLandscape.frame;
        }
        [self.scrollViewLandscape addSubview:glView];
        self.scrollViewLandscape.zoomScale = 1.0;
        
        if( mCodecId == MEDIA_CODEC_VIDEO_MJPEG ) {
            [self.scrollViewLandscape bringSubviewToFront:monitorLandscape/*self.glView*/];
        }
        else {
            [self.scrollViewLandscape bringSubviewToFront:/*monitorLandscape*/self.glView];
        }
        
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
        [self.navigationController setNavigationBarHidden:YES animated:NO];
    }
    else {
        
        [monitorLandscape deattachCamera];
        [monitorPortrait attachCamera:camera];
        
        [self removeGLView:TRUE];
        self.view = self.portraitView;
        NSLog( @"video frame {%d,%d}%dx%d", (int)self.monitorPortrait.frame.origin.x, (int)self.monitorPortrait.frame.origin.y, (int)self.monitorPortrait.frame.size.width, (int)self.monitorPortrait.frame.size.height);
        if( glView == nil ) {
            glView = [[CameraShowGLView alloc] initWithFrame:self.monitorPortrait.frame];
            [glView setMinimumGestureLength:100 MaximumVariance:50];
            glView.delegate = self;
            [glView attachCamera:camera];
        }
        else {
            [self.glView destroyFramebuffer];
            self.glView.frame = self.monitorPortrait.frame;
        }
        [self.monitorPortrait addSubview:glView];
        
        if( mCodecId == MEDIA_CODEC_VIDEO_MJPEG ) {
            [self.portraitView bringSubviewToFront:monitorPortrait/*self.glView*/];
        }
        else {
            [self.monitorPortrait bringSubviewToFront:/*monitorPortrait*/self.glView];
        }
        
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
    }
}
#else
- (void)changeOrientation:(UIInterfaceOrientation)orientation {
      
    NSLog(@"change orientation");

    if (orientation == UIInterfaceOrientationLandscapeLeft ||
        orientation == UIInterfaceOrientationLandscapeRight) {
        
        [monitorPortrait deattachCamera];
        [monitorLandscape attachCamera:camera];
        
        self.view = self.landscapeView;  
        
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
        [self.navigationController setNavigationBarHidden:YES animated:NO];
    }
    else {
        
        [monitorLandscape deattachCamera];
        [monitorPortrait attachCamera:camera];
        
        self.view = portraitView;        
        
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
    }
}
#endif

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    
    [self changeOrientation:toInterfaceOrientation];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
    
    
    
    self.loading.hidesWhenStopped = YES;

    
    
#if defined(LIB_140210)
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(cameraStopShowCompleted:) name: @"CameraStopShowCompleted" object: nil];
#endif
    
#if defined(STYLE_BLUE_AIC)
    self.portraitView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_blue_1.png"]];
    
    [statusLabel setTextColor:[UIColor whiteColor]];
    [videoInfoLabel setTextColor:[UIColor whiteColor]];
    [frameInfoLabel setTextColor:[UIColor whiteColor]];
    
    [playButton setTintColor:[UIColor whiteColor]];
    [pauseButton setTintColor:[UIColor whiteColor]];

    [self.toolBar setBackgroundImage:[UIImage imageNamed:@"bg_blue_b.png"] forToolbarPosition:UIBarPositionBottom barMetrics:UIBarMetricsDefault];
#endif
    
    toolBar.items = [NSArray arrayWithObjects:playButton, nil];
    playbackChannelIndex = -1;
    
#ifndef MacGulp
    ////self.navigationItem.prompt = camera.name;
#else    
    NSString *evtTime;
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:self.event.eventTime];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setLocale:[NSLocale currentLocale]];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];    
    evtTime = [dateFormatter stringFromDate:date];    
    [dateFormatter release];
    [date release];
    
    self.navigationItem.title = [NSString stringWithFormat:@"%@", evtTime];
#endif
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@" "
                                   style:UIBarButtonItemStylePlain
                                   target:self
                                   action:@selector(back:)];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(15, 4, 25, 25);
    //self.navigationItem.leftBarButtonItem = addButton;
#if defined(P2PNEX)
    //[backButton setImage:[UIImage imageNamed:@"nex_back3%.png"]];
    [btn setBackgroundImage:[UIImage imageNamed:@"nex_back3%.png"] forState:UIControlStateNormal];
    
#else
    //[backButton setImage:[UIImage imageNamed:@"_back%3x.png"]];
    [btn setBackgroundImage:[UIImage imageNamed:@"_back%3x.png"] forState:UIControlStateNormal];
#endif
    [btn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *bbnt = [[UIBarButtonItem alloc] initWithCustomView:btn];
    backButton = bbnt;
    
    self.navigationItem.leftBarButtonItem = backButton;
    [backButton release];
    
    [self.monitorPortrait setMinimumGestureLength:100 MaximumVariance:50];
    [self.monitorPortrait setUserInteractionEnabled:YES];
    self.monitorPortrait.backgroundColor = [UIColor blackColor];
    self.monitorPortrait.delegate = self;
    
    [self.monitorLandscape setMinimumGestureLength:100 MaximumVariance:50];
    [self.monitorLandscape setUserInteractionEnabled:YES];
    self.monitorLandscape.contentMode = UIViewContentModeScaleToFill;
    self.monitorLandscape.backgroundColor = [UIColor blackColor];
    self.monitorLandscape.delegate = self;
    

    
    self.scrollViewLandscape.minimumZoomScale = ZOOM_MIN_SCALE;
    self.scrollViewLandscape.maximumZoomScale = ZOOM_MAX_SCALE;
    self.scrollViewLandscape.contentMode = UIViewContentModeScaleToFill;
    self.scrollViewLandscape.contentSize = self.scrollViewLandscape.frame.size;
    
    [self changeOrientation:self.interfaceOrientation];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillResignActive:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidBecomeActive:)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
    
    seekTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(70.0f, 20.0f, 45.0f, 10.0f)];
    seekTimeLabel.font=[UIFont systemFontOfSize:10];
    [seekTimeLabel setText:@"00:00"];
    //myLabel.backgroundColor = [UIColor clearColor];
    seekTimeLabel.textAlignment=UITextAlignmentCenter;
    UIBarButtonItem *myButtonItem1 = [[UIBarButtonItem alloc]initWithCustomView:seekTimeLabel];
    NSMutableArray *toolbarItems1 = [NSMutableArray arrayWithArray:[toolBar items]];
    [toolbarItems1 addObject: myButtonItem1];
    [myButtonItem1 release];
    toolBar.items = toolbarItems1;
    
    playbackSlider = [[UISlider alloc] initWithFrame:CGRectMake(120.0f, 20.0f, 140.0f, 10.0f)];
    UIBarButtonItem *myButtonItem2 = [[UIBarButtonItem alloc]initWithCustomView:playbackSlider];
    NSMutableArray *toolbarItems2 = [NSMutableArray arrayWithArray:[toolBar items]];
    [toolbarItems2 addObject: myButtonItem2];
    [myButtonItem2 release];
    toolBar.items = toolbarItems2;
    
    [playbackSlider addTarget:self action:@selector(sliderAgeTouchDown) forControlEvents:UIControlEventTouchDown];
    //滑块拖动时的事件
    [playbackSlider addTarget:self action:@selector(sliderAgeValueChanged) forControlEvents:UIControlEventValueChanged];
    //滑动拖动后的事件
    [playbackSlider addTarget:self action:@selector(sliderAgeDragUp) forControlEvents:UIControlEventTouchUpInside];
    
    [playbackSlider setMinimumValue:0.0f];
    [playbackSlider setMaximumValue:0.0f];
    [playbackSlider setValue:0.0f];
    
#if 0
    //左右轨的图片
    UIImage *stetchLeftTrack= [UIImage imageNamed:@"pet_line_lightblue.png"];
    UIImage *stetchRightTrack = [UIImage imageNamed:@"pet_line_grey.png"];
    //滑块图片
    UIImage *thumbImage = [UIImage imageNamed:@"pet_slide_circle_lightblue.png"];
    
    
    /*
     sliderA.minimumValueImage = [UIImage imageNamed:@"设置slider左边的图片"];
     sliderA.maximumValueImage = [UIImage imageNamed:@"设置slider右边的图片"];
     //设置了会减小滚动区域的宽度，但整个slider的宽度不变
     */
    
    
    [self.ageSlider setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
    [self.ageSlider setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
    //注意这里要加UIControlStateHightlighted的状态，否则当拖动滑块时滑块将变成原生的控件
    [self.ageSlider setThumbImage:thumbImage forState:UIControlStateHighlighted];
    [self.ageSlider setThumbImage:thumbImage forState:UIControlStateNormal];
    //滑块拖动时的事件
    [self.ageSlider addTarget:self action:@selector(sliderAgeValueChanged) forControlEvents:UIControlEventValueChanged];
    //滑动拖动后的事件
    [self.ageSlider addTarget:self action:@selector(sliderAgeDragUp) forControlEvents:UIControlEventTouchUpInside];
    
#endif
    
    seekTimeTotalLabel = [[UILabel alloc] initWithFrame:CGRectMake(260.0f, 20.0f, 45.0f, 10.0f)];
    seekTimeTotalLabel.font=[UIFont systemFontOfSize:10];
    [seekTimeTotalLabel setText:@"00:00"];
    //myLabel.backgroundColor = [UIColor clearColor];
    seekTimeTotalLabel.textAlignment=UITextAlignmentCenter;
    UIBarButtonItem *myButtonItem3 = [[UIBarButtonItem alloc]initWithCustomView:seekTimeTotalLabel];
    NSMutableArray *toolbarItems3 = [NSMutableArray arrayWithArray:[toolBar items]];
    [toolbarItems3 addObject: myButtonItem3];
    [myButtonItem3 release];
    toolBar.items = toolbarItems3;
    
    playbackSeekTimeCurSec = 0;
    playbackSeekTimeTotalSec = 0;
    
    isUpdateCurrentStatus = YES;
    

    
    [super viewDidLoad];
    [self setNavigationStyle];
}


- (void)setNavigationStyle{
    
    [self setNavigationTitle:@"录像回放" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    
}

- (void)viewDidUnload {
    
    if (tmrRecvPlayback != nil) {
        
        [tmrRecvPlayback invalidate];
        tmrRecvPlayback = nil;
    }
    
    if (recordingTimer != nil) {
        
        [recordingTimer invalidate];
        recordingTimer = nil;
    }
    
    self.camera = nil;
    self.playButton = nil;
    self.pauseButton = nil;
    self.toolBar = nil;
    self.statusLabel = nil;
    self.videoInfoLabel = nil;
    self.frameInfoLabel = nil;
    self.portraitView = nil;
    self.landscapeView = nil;
    self.monitorPortrait = nil;
    self.monitorLandscape = nil;
    self.scrollViewLandscape = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:UIApplicationWillResignActiveNotification];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:UIApplicationDidBecomeActiveNotification];

#ifdef LIB_140210
    if(glView) {
        [self.glView tearDownGL];
        //[self.glView release];
        self.glView = nil;
    }
    CVPixelBufferRelease(mPixelBuffer);
    CVPixelBufferPoolRelease(mPixelBufferPool);
#endif
    
    [seekTimeLabel release];
    seekTimeLabel = nil;
    [seekTimeTotalLabel release];
    seekTimeTotalLabel = nil;
    [playbackSlider release];
    playbackSlider = nil;
    
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated {
    
    if (camera != nil)
        camera.delegate2 = self;
    
    [self play:nil];
    
    NSString *evtName;
    NSString *evtTime;
    
    evtName = [Event getEventTypeName:self.event.eventType];       
    
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:self.event.eventTime];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setLocale:[NSLocale currentLocale]];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];    
    evtTime = [dateFormatter stringFromDate:date];    
    [dateFormatter release];
    [date release];
    
    self.navName.text = [NSString stringWithFormat:@"%@", evtName];
    self.navTime.text = [NSString stringWithFormat:@"%@", evtTime];
    [self.loading setHidden:NO];
    [self.loading startAnimating];
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated 
{    
    [tmrRecvPlayback invalidate];
    tmrRecvPlayback = nil;
    
    [recordingTimer invalidate];
    recordingTimer = nil;
    
    [super viewWillDisappear:animated];
}

- (void)dealloc
{    
    [self.camera release];
    [self.playButton release];
    [self.pauseButton release];
    [self.toolBar release];
    [self.statusLabel release];
    [self.videoInfoLabel release];
    [self.frameInfoLabel release];
    [self.portraitView release];
    [self.landscapeView release];
    [self.monitorPortrait release];
    [self.monitorLandscape release];
    [self.scrollViewLandscape release];
    
    [super dealloc];
}

#pragma mark - MyCameraDelegate Methods
- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size
{ 
    if (camera_ == camera && type == IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL_RESP) {
        
        SMsgAVIoctrlPlayRecordResp1 *resp = (SMsgAVIoctrlPlayRecordResp1 *) data;
        
        switch (resp->command) {
            
            case AVIOCTRL_RECORD_PLAY_START:
            {
                
       
                
                if (isOpened) {
             
                    if (resp->result > 0 && resp->result <= 32) {

                        playbackChannelIndex = resp->result;
                        
#ifdef LIB_140210
                        [camera start4EventPlayback:playbackChannelIndex];
                        [camera startShow:playbackChannelIndex ScreenObject:self];
#else
                        [camera start:playbackChannelIndex];
                        [camera startShow:playbackChannelIndex];
#endif
                        [camera startSoundToPhone:playbackChannelIndex];
                        
                        isPaused = false;
                        
                        [self.loading setHidden:YES];
                        [self.loading stopAnimating];
                    }
                }
                
                NSUInteger seekTimeUsec = 0;
                seekTimeUsec = resp->reserved_;
                NSLog(@"seekTimeUsec=%lu", (unsigned long)seekTimeUsec);
                playbackSeekTimeTotalSec = seekTimeUsec / 1000;
                
                playbackSeekTimeCurSec = 0.0f;
                
                [playbackSlider setMinimumValue:0.0f];
                [playbackSlider setMaximumValue:playbackSeekTimeTotalSec];
                [playbackSlider setValue:playbackSeekTimeCurSec];

                [self updateViewInitStatus];
                
                break;
            }
            case AVIOCTRL_RECORD_PLAY_PAUSE:
            {
                /*
                isPaused = !isPaused;

                if (isPaused) 
                    [self showPlayButton];                
                else 
                    [self showPauseButton];
                */
                
                break;
            }
            case AVIOCTRL_RECORD_PLAY_STOP:
            {
                [camera stopSoundToPhone:playbackChannelIndex];
                [camera stopShow:playbackChannelIndex];
                [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
                [camera stop:playbackChannelIndex];

                isPaused = false;
                
                [self showPlayButton];
                
                playbackChannelIndex = -1;
                
                break;
            }
                
            case AVIOCTRL_RECORD_PLAY_END:
            {
                [camera stopSoundToPhone:playbackChannelIndex];
                [camera stopShow:playbackChannelIndex];
                [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
                [camera stop:playbackChannelIndex];
                
                SMsgAVIoctrlPlayRecord *req = (SMsgAVIoctrlPlayRecord *) malloc(sizeof(SMsgAVIoctrlPlayRecord));
                memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord));
                
                req->channel = 0;
                req->command = AVIOCTRL_RECORD_PLAY_STOP;
                req->stTimeDay = [Event getTimeDay:event.eventTime];
                req->Param = event.eventType;
                
                [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord)];
                
                free(req);

                isPaused = false;
                isOpened = false;
                playbackChannelIndex = -1;

                [SVProgressHUD showInfoWithStatus:@"此录像文件已播放完毕"];
                [self.navigationController popViewControllerAnimated:YES];
                
                if (tmrRecvPlayback != nil) {
                    
                    [tmrRecvPlayback invalidate];
                    tmrRecvPlayback = nil;
                }
                
                if (recordingTimer != nil) {
                    
                    [recordingTimer invalidate];
                    recordingTimer = nil;
                }
                
                break;
            }
            default:
                break;                
        }
    }
}

#ifdef LIB_140210
- (void)camera:(MyCamera *)camera_ _didReceiveFrameInfoWithVideoWidth:(NSInteger)videoWidth VideoHeight:(NSInteger)videoHeight VideoFPS:(NSInteger)fps VideoBPS:(NSInteger)videoBps AudioBPS:(NSInteger)audioBps OnlineNm:(NSInteger)onlineNm FrameCount:(unsigned int)frameCount IncompleteFrameCount:(unsigned int)incompleteFrameCount {
    
    if (camera_ == camera) {
       if( videoWidth > 1920 || videoHeight > 1080 ) {
            NSLog( @"!!!!!!!! ERROR !!!!!!!!" );
           // return;
        }
       
      
        CGSize maxZoom = CGSizeMake((videoWidth*2.0 > 1920)?1920:videoWidth*2.0, (videoHeight*2.0 > 1080)?1080:videoHeight*2.0);
        if( glView && videoWidth > 0 && videoHeight > 0 ) {
            [self recalcMonitorRect:CGSizeMake(videoWidth, videoHeight)];
            self.glView.maxZoom = maxZoom;
        }
     
        if( maxZoom.width / self.scrollViewLandscape.frame.size.width > 1.0 ) {
            self.scrollViewLandscape.maximumZoomScale = maxZoom.width / self.scrollViewLandscape.frame.size.width;
        }
        else {
            self.scrollViewLandscape.maximumZoomScale = 1;
        }
        
        self.navvideoInfoLabel.text = [NSString stringWithFormat:@"%dx%d / FPS: %d / BPS: %d Kbps", videoWidth, videoHeight, fps, (videoBps + audioBps) / 1024];
        self.navframeInfoLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Frame ratio: %d / %d", @"Used for display channel information"),  incompleteFrameCount, frameCount];
    }
}

#pragma mark - MonitorTouchDelegate Methods
- (void)monitor:(Monitor *)monitor gestureSwiped:(Direction)direction {
    NSLog( @"Ignore PTZ in Playback mode." );
}

- (void)gestureSwiped:(Direction)direction {
    
}

- (void)gesturePinched:(CGFloat)scale {
    if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
        self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        
        NSLog( @"CameraPlaybackController - Pinched [Landscape] scale:%f/%f", scale, self.scrollViewLandscape.maximumZoomScale );
        if( scale <= self.scrollViewLandscape.maximumZoomScale )
            [self.scrollViewLandscape setZoomScale:scale animated:YES];
    }
    else {

        
    }
}

#pragma mark - ScrollView Delegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    
    if (self.interfaceOrientation == UIInterfaceOrientationPortrait) {
        return self.monitorPortrait;
    }
    else if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
             self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        return self.monitorLandscape;
    }
    else return nil;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView
                       withView:(UIView *)view
                        atScale:(CGFloat)scale {
    if( glView ) {
        glView.frame = CGRectMake( 0, 0, scrollView.frame.size.width*scale, scrollView.frame.size.height*scale );
        NSLog( @"{0,0,%d,%d}", (int)(scrollView.frame.size.width*scale), (int)(scrollView.frame.size.height*scale) );
    }
}

#else
- (void)camera:(MyCamera *)camera_ _didReceiveFrameInfoWithVideoWidth:(NSInteger)videoWidth VideoHeight:(NSInteger)videoHeight VideoFPS:(NSInteger)fps VideoBPS:(NSInteger)videoBps AudioBPS:(NSInteger)audioBps OnlineNm:(NSInteger)onlineNm FrameCount:(unsigned long)frameCount IncompleteFrameCount:(unsigned long)incompleteFrameCount {
    
    if (camera_ == camera) {
        
        self.videoInfoLabel.text = [NSString stringWithFormat:@"%ldx%ld / FPS: %ld / BPS: %ld Kbps", (long)videoWidth, (long)videoHeight, (long)fps, (videoBps + audioBps) / 1024]; 
        self.frameInfoLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Frame ratio: %d / %d", @"Used for display channel information"),  incompleteFrameCount, frameCount];
    }
}


#pragma mark - MonitorTouchDelegate Methods
- (void)gestureSwiped:(Direction)direction {
    
}

- (void)gesturePinched:(CGFloat)scale {    
    
    if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {
        
        [self.scrollViewPortrait setZoomScale:scale animated:YES];
    }
    else if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft ||
             [[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) {
        
        [self.scrollViewLandscape setZoomScale:scale animated:YES];
    }
}

#pragma mark - ScrollView Delegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    
    if (self.interfaceOrientation == UIInterfaceOrientationPortrait) {
        return self.monitorPortrait;
    }
    else if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
             self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        return self.monitorLandscape;
    }
    else return nil;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView 
                       withView:(UIView *)view 
                        atScale:(float)scale {
    
    if (scale == ZOOM_MIN_SCALE) {
        
        if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {
            
            self.scrollViewPortrait.contentSize = CGSizeMake(320, 240);
        }
        else if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft ||
                 [[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) {
            
            self.scrollViewLandscape.contentSize = CGSizeMake(320, 240);
        }
    }
}
#endif

#pragma mark - UIApplication Delegate
- (void)applicationWillResignActive:(NSNotification *)notification
{
    if (playbackChannelIndex >= 0) {
        
        SMsgAVIoctrlPlayRecord *req = (SMsgAVIoctrlPlayRecord *) malloc(sizeof(SMsgAVIoctrlPlayRecord));
        memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord));
        
        req->channel = 0;
        req->command = AVIOCTRL_RECORD_PLAY_PAUSE;
        req->stTimeDay = [Event getTimeDay:event.eventTime];
        req->Param = event.eventType;
        
        [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord)];
        
        free(req);
    }
}

- (void)applicationDidBecomeActive:(NSNotification *)notification
{
    if (playbackChannelIndex >= 0) {
        
        SMsgAVIoctrlPlayRecord *req = (SMsgAVIoctrlPlayRecord *) malloc(sizeof(SMsgAVIoctrlPlayRecord));
        memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord));
        
        req->channel = 0;
        req->command = AVIOCTRL_RECORD_PLAY_PAUSE;
        req->stTimeDay = [Event getTimeDay:event.eventTime];
        req->Param = event.eventType;
        
        [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord)];
        
        free(req);
    }
}

#if defined(LIB_140210)
- (void)updateToScreen:(NSValue*)pointer
{
    LPSIMAGEBUFFINFO pScreenBmpStore = (LPSIMAGEBUFFINFO)[pointer pointerValue];
    [glView renderVideo:pScreenBmpStore->pixelBuff];
    
}

- (void)recalcMonitorRect:(CGSize)videoframe
{
   #pragma mark - --------------------------旋转--------------------------
    
    if( self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
       self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && UIInterfaceOrientationIsLandscape(self.interfaceOrientation) ) {
            CGFloat fTmp = screenRect.size.height;
            screenRect.size.height = screenRect.size.width;
            screenRect.size.width = fTmp;
        }
        CGFloat screenWidth = screenRect.size.width;
        CGFloat screenHeight = screenRect.size.height;
        
        screenRect.size.height =screenWidth ;
        screenRect.size.width = screenHeight;
        
        
        self.glView.parentFrame = CGRectMake(0, 0, SCREEN_WIDTH, self.monitorLandscape.frame.size.height);
        self.glView.frame = CGRectMake(0, 0, SCREEN_WIDTH,self.monitorLandscape.frame.size.height);
    }
    else {
        self.glView.parentFrame = CGRectMake(0, 0, self.monitorPortrait.frame.size.width, self.monitorPortrait.frame.size.height);
        self.glView.frame = CGRectMake(0, 0, self.monitorPortrait.frame.size.width,self.monitorPortrait.frame.size.height);
    }
}

// If you want to set the final frame size, just implement this delegation to given the wish frame size
//
- (void)glFrameSize:(NSArray*)param
{
    CGSize* pglFrameSize_Original = (CGSize*)[(NSValue*)[param objectAtIndex:0] pointerValue];
    CGSize* pglFrameSize_Scaling = (CGSize*)[(NSValue*)[param objectAtIndex:1] pointerValue];
    
    [self recalcMonitorRect:*pglFrameSize_Original];
    self.glView.maxZoom = CGSizeMake( (pglFrameSize_Original->width*2.0 > 1920)?1920:pglFrameSize_Original->width*2.0, (pglFrameSize_Original->height*2.0 > 1080)?1080:pglFrameSize_Original->height*2.0 );
    
    *pglFrameSize_Scaling = self.glView.frame.size;
}

- (void)reportCodecId:(NSValue*)pointer
{
    unsigned short *pnCodecId = (unsigned short *)[pointer pointerValue];
    
    mCodecId = *pnCodecId;
    
    if( mCodecId == MEDIA_CODEC_VIDEO_MJPEG ) {
        if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
            self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
            
            [self.scrollViewLandscape bringSubviewToFront:monitorLandscape/*self.glView*/];
        }
        else {
           // [self.scrollViewPortrait bringSubviewToFront:monitorLandscape/*self.glView*/];
        }
    }
    else {
        if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
            self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
            
         //   [self.scrollViewLandscape bringSubviewToFront:/*monitorLandscape*/self.glView];
        }
        else {
            [self.monitorPortrait bringSubviewToFront:/*monitorLandscape*/self.glView];
        }
    }
}



- (void)cameraStopShowCompleted:(NSNotification *)notification
{
    bStopShowCompletedLock = TRUE;
}
#endif

- (void)waitStopShowCompleted:(unsigned int)uTimeOutInMs
{
    unsigned int uStart = _getTickCountCamPlaB();
    while( self.bStopShowCompletedLock == FALSE ) {
        usleep(1000);
        unsigned int now = _getTickCountCamPlaB();
        if( now - uStart >= uTimeOutInMs ) {
            NSLog( @"CameraPlaybackController - waitStopShowCompleted !!!TIMEOUT!!!" );
            break;
        }
    }
    
}

- (NSString *)intToStringTime:(NSUInteger)sec {
    NSString *str = @"";
    
    NSUInteger m = sec / 60;
    NSUInteger s = sec % 60;
    
    if (m < 10 && s < 10) {
        str = [NSString stringWithFormat:@"0%ld:0%ld", (unsigned long)m, (unsigned long)s];

    }
    else if (m < 10 && s >= 10) {
        str = [NSString stringWithFormat:@"0%ld:%ld", (unsigned long)m, (unsigned long)s];
    }
    else if (m >= 10 && s < 10) {
        str = [NSString stringWithFormat:@"%ld:0%ld", (unsigned long)m, (unsigned long)s];
    }
    else {
        str = [NSString stringWithFormat:@"%ld:%ld", (unsigned long)m, (unsigned long)s];
    }
    
    
    return str;
}

- (void)updateViewInitStatus {
    [seekTimeLabel setText:[self intToStringTime:playbackSeekTimeCurSec]];
    [seekTimeTotalLabel setText:[self intToStringTime:playbackSeekTimeTotalSec]];
}

- (void)updateViewCurrentStatus {

    [seekTimeLabel setText:[self intToStringTime:playbackSeekTimeCurSec]];
    
}

- (void)sliderAgeTouchDown{
    int progressAsInt = (int)playbackSlider.value;
    NSLog(@"sliderAgeTouchDown progressAsInt:%d", progressAsInt);
    
    isUpdateCurrentStatus = NO;
}

- (void)sliderAgeValueChanged{
    int progressAsInt = (int)playbackSlider.value;
    NSLog(@"sliderAgeValueChanged progressAsInt:%d", progressAsInt);
    
    if (isOpened == true && isPaused == false) {
    
        playbackSeekTimeCurSec = progressAsInt;
    
        [self updateViewCurrentStatus];
    }
}

- (void)sliderAgeDragUp {
    
    NSLog(@"sliderAgeDragUp isOpened:%d, isPaused:%d", isOpened, isPaused);
    if (isOpened == true && isPaused == false) {
        int progressAsInt = (int)playbackSlider.value;
        NSLog(@"sliderAgeDragUp progressAsInt:%d", progressAsInt);
        
        isUpdateCurrentStatus = YES;
        
        if (recordingTimer != nil) {
            
            [recordingTimer invalidate];
            recordingTimer = nil;
        }
        recordingTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerRecording:) userInfo:nil repeats:YES];
        //recordingTimes = 0;
        playbackSeekTimeCurSec = progressAsInt;
        
        if (playbackSeekTimeTotalSec == 0) {
            return;
        }
        
        float par = playbackSeekTimeCurSec*1.0f/playbackSeekTimeTotalSec;
        NSLog(@"playbackSeekTimeCurSec:%lu, playbackSeekTimeTotalSec:%lu, par:%f", (unsigned long)playbackSeekTimeCurSec, (unsigned long)playbackSeekTimeTotalSec, par);
        
        SMsgAVIoctrlPlayRecord1 *req = (SMsgAVIoctrlPlayRecord1 *) malloc(sizeof(SMsgAVIoctrlPlayRecord1));
        memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord1));
        
        req->channel = 0;
        req->command = AVIOCTRL_RECORD_PLAY_SEEKTIME;
        req->stTimeDay = [Event getTimeDay:event.eventTime];
        req->Param = event.eventType;
        req->reserved_ = par * 100;
        
        
        
        NSLog(@"req->reserved_:%d", req->reserved_);
        
        [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord1)];
        
        free(req);
    } else {
        
        NSLog(@"sliderAgeDragUp playbackSeekTimeCurSec:%lu", (unsigned long)playbackSeekTimeCurSec);
        [playbackSlider setValue:playbackSeekTimeCurSec animated:YES];
    }
}

- (void)startRecordingTimer {
    // status
    [recordingTimer setFireDate:[NSDate distantPast]];
}

- (void)stopRecordingTimer {
    // status
    [recordingTimer setFireDate:[NSDate distantFuture]];
}

@end
